/*
 * common.h - 通用定义和结构体声明
 * 作者: tjc
 * 时间: 2025-09-06
 * 版本: v1.4
*/
#ifndef __COMMON_H__
#define __COMMON_H__

#include <sqlite3.h>

//消息头结构体
typedef struct msghead
{
	char magic[4];
	char version;
	char msgtype;
	char datatype;
	char resv;
	unsigned int timestamp;
	unsigned int sequence;
	unsigned int datasize;
}msghead_t;

//返回消息体
typedef struct msgresp
{
	int result;
	char desc[32];
	char data[64];
}msgresp_t;

//注册请求结构体
typedef struct register_request
{
	char serial[32];
	char mac[12];
	char timestamp[16];
	char sign[32];
	char type[32];
}register_request_t;

//注册响应结构体
typedef struct register_response {
	char uuid[32];
	char passwd[32];
} register_response_t;

//登录请求结构体
typedef struct login_request
{
	char uuid[32];
	char version[64];
	char timestamp[16];
	char sign[32];
}login_request_t;

//添加人员结构体
typedef struct add_person_request
{
	char personId[32];
	char personCode[16];
	char name[24];
	int type;
	char idNum[20];
	char icNum[8];
	int passNum;
	char passPeriod[36];
}add_person_request_t;

//更新人员
typedef struct update_person_request
{
	char personId[32];
	char personCode[16];
	char name[24];
	int type;
	char idNum[20];
	char icNum[8];
	int passNum;
	char passPeriod[36];
}update_person_request_t;

//删除人员
typedef struct delete_person_request
{
	char idSet[32];
}delete_person_request_t;

typedef enum {
	CMD_ADD_PERSON = 1,
	CMD_UPDATE_PERSON,
	CMD_DELETE_PERSON,
	CMD_CLEAR_PERSONS,
	CMD_SYNC_PERSONS
} command_type_t;

typedef struct control_command {
	command_type_t type;
	char data[256]; // 根据命令类型存储不同数据
} control_command_t;


#define MAGIC "TEST"
#define MSGVERSION 2
#define RESV '1'

//msgtype
#define HEARTBEAT 1
#define REQUEST 2
#define RESPONSE 3

//datatype
#define  REGISTER 0x11
#define  LOGIN 0x12
#define  ADDPERSON 0x13
#define  UPDATEPERSON 0x14
#define  DELPERSON 0x15
#define  CLRPERSON 0X16


#define MAX_TRY 3
#define HEARTBEAT_TIME 25
#define RESPONSE_TIME 20

#define MSG_QUEUE_FILE "./device_msg_queue"

extern int g_register;
extern int g_login;
extern char g_uuid[32];
extern char g_passwd[32];

int recv_msg(int sockfd,char *buf);

int send_msg(int sockfd,char msgType,char dataType,void *data,int size);

int server_process_msg(int sockfd,char *buf);

int client_process_msg(int sockfd,char *buf);

int register_handler(register_request_t *reg,char *uuid,char *passwd);

int login_handler(login_request_t *login);

int distribute_person_handler(add_person_request_t *person);

int add_person_handler(add_person_request_t *person);

int update_person_handler(update_person_request_t *person);

int delete_person_handler(delete_person_request_t *del_req);

int clear_person_handler();

int database_init();

int save_to_database(char *table,void *data);

int generate_signature(char *str1,char *str2,char *str3,char *output);

int check_message_queue(int sockfd);

int process_control_command(control_command_t *cmd,int sockfd);

int distribute_all_persons();
#endif

